const {
  createNewsCategoryService,
  createNewsService,
} = require("../../service/news");
const { ErrorRes, SuccessRes } = require("../../res-model/index");
const {
  createNewsCategoryFailInfo,
  createNewsFailInfo,
} = require("../../res-model/failInfo/news");
/**
 * @description 创建新闻
 * @returns
 */
async function createNews(data) {
  console.log("data", data);
  // authorName 默认admin
  const { cId, title, authorName, content } = data;
  if (!cId) {
    // 标题不能为空
    return new ErrorRes(createNewsFailInfo, "新闻分类Id不能为空");
  }
  if (!title) {
    // 标题不能为空
    return new ErrorRes(createNewsFailInfo, "新闻标题不能为空");
  }
  if (!content) {
    // 新闻内容不能为空
    return new ErrorRes(createNewsFailInfo, "新闻内容不能为空");
  }
  let newNews;
  try {
    newNews = await createNewsService(data);
  } catch (ex) {
    console.error("创建新闻失败", ex);
    return new ErrorRes(createNewsFailInfo); // 数据库错误
  }
  // 创建失败
  if (newNews == null) return new ErrorRes(createNewsFailInfo, "创建新闻失败");

  // 创建成功
  return new SuccessRes(newNews);
}
/**
 * @description 创建新闻分类
 * @returns
 */
async function createNewsCategory(data) {
  const { name } = data;
  if (!name) {
    // 标题不能为空
    return new ErrorRes(createNewsCategoryFailInfo, "新闻分类名不能为空");
  }
  let newNewsCategory;
  try {
    newNewsCategory = await createNewsCategoryService(data);
  } catch (ex) {
    console.error("创建新闻分类失败", ex);
    return new ErrorRes(createNewsCategoryFailInfo); // 数据库错误
  }
  // 创建失败
  if (newNewsCategory == null)
    return new ErrorRes(createNewsCategoryFailInfo, "创建新闻分类失败");

  // 创建成功
  return new SuccessRes(newNewsCategory);
}
module.exports = {
  createNews,
  createNewsCategory,
};
